package com.ljm.shiro.filter;

import com.alibaba.fastjson.JSONObject;
import com.ljm.common.dto.BaseResult;
import com.ljm.common.enums.ResultStatus;
import com.ljm.common.util.ResultUtil;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 版权：    Copyright by ljm
 * 描述：
 * 修改人：  HuamingChen
 * 修改时间：2018/12/12
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */
public class ShiroFormAuthenticationFilter extends FormAuthenticationFilter {
    /**
     * 日志
     */
    private static final Logger LOG = LoggerFactory.getLogger(ShiroFormAuthenticationFilter.class);

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
            throws Exception {
        if (this.isLoginRequest(request, response)) {
            if (this.isLoginSubmission(request, response)) {// isLoginSubmission只有同时是post才会返回true
                return true;
            } else {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Login page view.");
                }
                return true;
            }
        } else {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Attempting to access a path which requires authentication.  Forwarding to the Authentication {}",this.getLoginUrl());
            }
            //其余情况，重新登录
            HttpServletResponse httpResponse = WebUtils.toHttp(response);
            httpResponse.setContentType("application/json");
            httpResponse.setCharacterEncoding("UTF-8");
            PrintWriter out = httpResponse.getWriter();
            BaseResult errorResult = ResultUtil.error(ResultStatus.NEED_LOGIN, "Please login!");
            out.println(JSONObject.toJSONString(errorResult));
            out.flush();
            out.close();
            return false;
        }

    }
}
